<template>
  <div>
    <n-modal
      :show="props.showModal"
      :on-mask-click="maskClick"
      :class="{ 'blow-up': isBlowUp }"
    >
      <n-card
        style="width: 50%; max-height: 60vh; min-width: 650px"
        :title="props.dialogTitle"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
        header-style="padding:20px;padding-bottom:10px;"
        content-style="overflow: hidden; overflow-y: auto;padding:20px;padding-top:0px;"
      >
        <template #header-extra>
          <n-button @click="closeModal" text size="tiny" color="#ff69b4">
            <template #icon>
              <n-icon size="20">
                <Close></Close>
              </n-icon>
            </template>
          </n-button>
        </template>
        <div style="margin: 20px 0px">
          <n-form
            label-placement="left"
            ref="formRef"
            :label-width="80"
            :model="formValue"
            :rules="rules"
            :size="size"
          >
            <n-form-item label="菜单名称" path="name">
              <n-input
                v-model:value="formValue.name"
                placeholder="请输入名称"
              />
            </n-form-item>
            <n-form-item label="菜单路由">
              <n-input
                v-model:value="formValue.router"
                placeholder="请输入路由"
              />
            </n-form-item>
            <n-form-item label="页面路径">
              <n-input
                v-model:value="formValue.pageUrl"
                placeholder="请输入路径"
              />
            </n-form-item>
            <n-form-item label="菜单类型" path="menuType">
              <n-select
                v-model:value="formValue.menuType"
                :options="menyTypeOptions"
              />
            </n-form-item>
            <n-form-item label="排序">
              <n-input-number
                style="width: 100%"
                v-model:value="formValue.sort"
                clearable
                placeholder="数字越大，排序越前"
              />
            </n-form-item>
            <n-form-item label="上级菜单">
              <n-tree-select
                placeholder="上级菜单"
                :options="menuTreeList"
                default-value="Drive My Car"
                @update:value="handleUpdateValue"
                key-field="id"
                label-field="name"
                children-field="children"
                :clearable="true"
                :default-expand-all="true"
              />
            </n-form-item>
            <n-form-item label="是否可用">
              <n-switch v-model:value="formValue.enable" size="medium">
                <template #checked> 可用 </template>
                <template #unchecked>禁用 </template>
                <template #checked-icon>
                  <n-icon :component="CheckmarkDoneCircleSharp" />
                </template>
                <template #unchecked-icon>
                  <n-icon :component="CloseCircleOutline" />
                </template>
              </n-switch>
            </n-form-item>
            <n-form-item label="菜单图标" path="previewFileList">
              <n-upload
                v-model:file-list="formValue.previewFileList"
                v-model:value="formValue.previewFileList"
                accept="image/png, image/jpeg"
                list-type="image-card"
                @preview="handlePreview"
                :max="1"
                :default-upload="false"
                :show-file-list="true"
                ref="uploadRef"
                :on-before-upload="handleBeforeRead"
                file-list-style="width:40px;height:40px;"
                trigger-style="width:40px;height:40px;"
                :show-preview-button="false"
                width="50px;"
              >
                <n-icon
                  size="20"
                  v-if="formValue.menuIcon != '' && formValue.menuIcon != null"
                >
                  <img
                    :src="formValue.menuIcon"
                    style="width: 100%; height: 100%"
                    alt=""
                  />
                </n-icon>
              </n-upload>
            </n-form-item>
          </n-form>
        </div>
        <template #action>
          <div
            style="
              margin: -15px;
              display: flex;
              justify-content: flex-end;
              gap: 10px;
            "
          >
            <n-button size="small" @click="closeModal">取消</n-button>
            <n-button size="small" type="primary" @click="handleValidateClick">
              确定
            </n-button>
          </div>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import {
  Close,
  CheckmarkDoneCircleSharp,
  CloseCircleOutline,
} from "@vicons/ionicons5";
import { useStore } from "vuex";
import { createMenuRequest } from "@/models/menuModel.ts";
import { createMenu, getMenuTree } from "@/api/menu.ts";

const props = defineProps({
  showModal: {
    type: Boolean,
    default: () => false,
  },
  data: {
    type: Array,
    default: "",
  },
  dialogTitle: {
    type: String,
    default: () => "新增菜单",
  },
});
const store = useStore();
const formRef: any = ref(null);
const isInitialize = ref(false); //控制初始化私密密码的页面显示
const isBlowUp = ref(false);
const formValue = ref<createMenuRequest>({
  parentID: null,
  name: "",
  router: "",
  pageUrl: "",
  menuType: 2,
  menuIcon: "",
  sort: 0,
  enable: true,
});
const rules = {
  name: {
    required: true,
    trigger: ["blur", "input"],
    message: "请给菜单一个名字",
  },
  menuType: {
    type: "number",
    required: true,
    trigger: ["blur", "change"],
    message: "菜单还没有类型",
  },
};

const menuTreeList = ref();
const menyTypeOptions = ref([
  {
    value: 1,
    label: "目录",
  },
  {
    value: 2,
    label: "菜单",
  },
  {
    value: 3,
    label: "按钮",
  },
]);
const uploadRef = ref<any>(null);
const imgData = ref();
const imgUrl = import.meta.env.VITE_APP_API_KEY;

const init = (row: any = null) => {
  menuTreeList.value = [];
  formValue.value.name = "";
  formValue.value.parentID = null;
  formValue.value.router = null;
  formValue.value.pageUrl = null;
  formValue.value.menuType = 2;
  formValue.value.menuIcon = null;
  formValue.value.sort = 0;
  formValue.value.enable = true;
  getMenuTree().then((res) => {
    menuTreeList.value = res.data;
  });
};
const getTreeChildren = (data) => {
  if (data == undefined || data == null) {
    return;
  }
  let children: any = [];
  data.forEach((d: any) => {
    children.push({
      label: d.t_name,
      value: d.t_id,
      children: getTreeChildren(d.children),
    });
  });

  return children.length == 0 ? null : children;
};
const handleBeforeRead = async ({ file }: any) => {
  // 创建 FileReader 对象
  const reader: any = new FileReader();
  console.log(file);
  reader.onload = () => {
    const blobUrl = reader.result as string;
    // console.log(blobUrl);
    // 将读取结果转换为 Base64 格式并进行处理
    const base64Data = reader.result.split(",")[1]; // 获取 base64 数据部分
    // 进行后续处理，比如发送到服务器等
    formValue.value.menuIcon = "data:image/png;base64," + base64Data;
    file.file.url = blobUrl;
  };

  // 读取文件并转换为 Data URL
  reader.readAsDataURL(file.file);
  // 你可以决定是否继续上传，返回true则继续，返回false则取消上传
  return false;
};
const handleUpdateValue = (value) => {
  formValue.value.parentID = value;
};
const maskClick = () => {
  isBlowUp.value = true;
  setTimeout(() => {
    isBlowUp.value = false;
  }, 500);
};
const emit = defineEmits(["closeModal", "getMenuListPage"]);

// 假设你有一个方法来切换模态框的显示状态
const closeModal = () => {
  emit("closeModal");
  isInitialize.value = false;
};
const handleValidateClick = (e) => {
  e.preventDefault();
  formRef.value?.validate((errors) => {
    if (!errors) {
      createMenu(formValue.value).then((res) => {
        if (res.code == 200) {
          window.$message.success(res.message);
          closeModal();
          emit("getMenuListPage");
        } else {
          window.$message.error(res.message);
        }
      });
    } else {
      console.log(formValue.value);
      window.$message.error("表单验证错误");
    }
  });
};
defineExpose({ init });
</script>

<style scoped>
.blow-up {
  animation: scaleAnimation 0.5s infinite;
  transform-origin: center center;
  /* 设置缩放中心为元素中心点 */
}

@keyframes scaleAnimation {
  0% {
    transform: scale(1);
    transform-origin: center center;
  }

  50% {
    transform: scale(1.1);
    /* 在动画中点缩放到1.1倍 */
    transform-origin: center center;
  }

  100% {
    transform: scale(1);
    /* 在动画结束时缩放回原始大小 */
    transform-origin: center center;
  }
}
</style>
